package com.itheima.ydd.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.List;
import java.util.UUID;

/**
 * 七牛云上传文件工具类
 */
@Slf4j
public class QiniuCloudUtil {

    // 设置需要操作的账号的AK和SK					（AK和SK均在七牛云中获得，以下会说明）
    private static final String ACCESS_KEY = "b2dLOhzyQncF4Vpl4XV48TDHtv6C9Zx-RIROKtwu";
    private static final String SECRET_KEY = "ZFb_2SN-uNRw5IOBfayXKrwpt_45JeUG-030teQO";

    // 要上传的空间								（刚刚新建空间的名称）
    private static final String BUCKETNAME = "zcscloud";

    // 密钥
    private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);

    //新建空间时，七牛云分配出的域名 （自己可在万网购买域名解析后，绑定到加速域名）
    private static final String DOMAIN = "qn.zcscloud.cn";

    public static String getUpToken() {
        return auth.uploadToken(BUCKETNAME, null, 3600, new StringMap().put("insertOnly", 1));
    }

    //base64方式上传
    /**
     * @Author 16372
     * @Description //TODO base64方式上传
     * @Date 14:41 2022/2/19
     * @Param [base64, key] 文件的Byte字节数组对象   文件名(请使用uuid生成,包含后缀)
     * @return java.lang.String 云盘访问路径
     **/
    public static String put64image(byte[] base64, String key) throws Exception {

        String upToken = getUpToken();

        Configuration cfg = new Configuration(Zone.zone0());

        UploadManager uploadManager = new UploadManager(cfg);
        try {
            //Response response = uploadManager.put(localFilePath, key, upToken);
            Response response = uploadManager.put(base64,"rg/"+key,upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println("============================================================================");
            System.out.println(DOMAIN +"/"+ putRet.key);
            System.out.println(putRet.hash);
            return "/"+DOMAIN +"/"+ putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
                ex2.printStackTrace();
                Response response = ex2.response;
                System.out.println(response.toString());
            }
        }
        return "";
    }

    /**
     * @Author 16372
     * @Description //TODO 将指定路径的文件上传到云服务器
     * @Date 15:16 2022/2/19
     * @Param [file, key]
     * @return java.lang.String 图片的网络路径
     **/
    public static String putFile(String url) throws Exception{
        String suffix = url.substring(url.lastIndexOf("."));

        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID().toString() + suffix;//dfsdfdfd.jpg

        File file = new File(url);
        String upToken = getUpToken();

        Configuration cfg = new Configuration(Zone.zone0());

        UploadManager uploadManager = new UploadManager(cfg);

        Response response = uploadManager.put(file, "yyd/"+fileName, upToken);
        //解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        System.out.println("============================================================================");
        System.out.println(DOMAIN +"/"+ putRet.key);
        System.out.println(putRet.hash);
        log.info("云端保存成功路径为{}",DOMAIN +"/"+ putRet.key);
        log.info("==============================================================================");
        return DOMAIN +"/"+ putRet.key;
    }

    /**
     * @param key 图片的文件名
     * @Explain 删除空间中的图片
     */
    public static void delete(String key) {
        Configuration cfg = new Configuration(Region.region0());
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(BUCKETNAME, key);
        } catch (Exception e) {
            //已被删除
        }
    }

    /**
     * @Author 16372
     * @Description //TODO 批量删除
     * @Date 11:34 2022/2/19
     * @Param [urls] 图片地址
     * @return void
     **/
    public static void deleteList(List<String> urls) {
        Configuration cfg = new Configuration(Region.region0());
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        for (String url : urls) {
            try {
                bucketManager.delete(BUCKETNAME, url);
            } catch (Exception e) {
                //已被删除

            }
        }

    }
}